package com.xjtu.platform.user.avatar;

/**
 * @创建人 mby381
 * @创建时间 2021-12-17
 * @描述
 */

import com.xjtu.platform.common.CommonService;
import com.xjtu.platform.common.CurrentUser;
import com.xjtu.platform.common.Result;
import com.xjtu.platform.common.TokenUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;


@RestController
@RequestMapping("/avatar")
public class AvatarAPI {

    @Resource
    private CommonService commonService;

    @Resource
    private AvatarService avatarService;

    @RequestMapping(value = "/avatar/{filename}",method = RequestMethod.GET)
    public void getAvatar(@PathVariable String filename, HttpServletResponse response) throws IOException {
        System.out.println("filename!");
        System.out.println(filename);
        InputStream in = new FileInputStream(CurrentUser.AVATAR_DIR+"/"+filename);
        OutputStream out = response.getOutputStream();

        byte[] b = new byte[10240];
        int len = -1;

        while((len=in.read(b))!=-1){
            out.write(b,0,len);
        }
        out.flush();
        out.close();
        in.close();
    }


    @RequestMapping(value = "/setavatar",method = RequestMethod.POST)
    public Result uploadAvatar(MultipartFile avatar, @RequestHeader("Token") String token) throws IOException {

        InputStream in = avatar.getInputStream();

        String name = UUID.randomUUID().toString();
        String submittedFilename = avatar.getOriginalFilename();
        String suffix = submittedFilename.substring(submittedFilename.lastIndexOf("."));
        String filename = name+suffix;
        filename = filename.replace('.','-');

        OutputStream out = new FileOutputStream(CurrentUser.AVATAR_DIR+"/"+filename);

        byte[] b = new byte[10240];
        int len = -1;

        while((len=in.read(b))!=-1){
            out.write(b,0,len);
        }
        out.flush();
        out.close();
        in.close();

        CurrentUser currentUser = TokenUtils.getUserInfo(token,commonService);

        avatarService.setAvatar(currentUser,filename);

        return Result.success();

    }


    @RequestMapping(value = "/get_curr-user",method = RequestMethod.GET)
    public Result getCurr_User(@RequestHeader("Token") String Token){
        try {
            CurrentUser currentUser = TokenUtils.getUserInfo(Token, commonService);
            return Result.success("查询成功", currentUser);
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.fail(400,"查询当前用户失败！");
    }


}
